#include "smarthome.h"
#include "ui_smarthome.h"
#include <QDebug>
#include "terminalconsole.h"

smartHome::smartHome(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::smartHome)
{
    ui->setupUi(this);
    //去窗口边框
    setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    //连接按钮的槽函数
    connect(ui->toolButton,SIGNAL(clicked()),this,SLOT(on_toolButton_clicked()));
    connect(ui->toolButton_2,SIGNAL(clicked()),this,SLOT(on_toolButton_2_clicked()));
    connect(ui->toolButton_3,SIGNAL(clicked()),this,SLOT(on_toolButton_3_clicked()));
    // 创建串口对象
    serialPort = new QSerialPort(this);

    if(serialPort->isOpen())//判断对象是否已经打开，如果是就关掉
       {
           serialPort->clear();
           serialPort->close();
       }
    // 设置串口名称、波特率等参数
    serialPort->setPortName("COM1"); // 根据实际情况修改串口名称
    serialPort->setBaudRate(QSerialPort::Baud9600);

    // 打开串口
    if (serialPort->open(QIODevice::ReadWrite)) {
        qDebug() << "串口打开成功";
    } else {
        qDebug() << "串口打开失败";
    }

}


smartHome::~smartHome()
{
    delete ui;
    // 关闭串口
    if (serialPort->isOpen()) {
        serialPort->close();
    }
    delete serialPort;
}

void smartHome::on_pushButton_5_clicked()//厨房灯
{
   sendData("A1","A2");
}

void smartHome::on_pushButton_6_clicked()//客厅灯
{
    sendData("B1","B2");
}

void smartHome::on_pushButton_7_clicked()//客厅窗帘
{
    sendData("B3","B4");
}

void smartHome::on_pushButton_8_clicked()//客厅窗帘
{
   sendData("B5","B6");
}

void smartHome::on_pushButton_9_clicked()//客厅电视
{
    sendData("B7","B8");
}

void smartHome::on_pushButton_10_clicked()//书房灯
{
    sendData("C1","C2");
}

void smartHome::on_pushButton_11_clicked()//主卧空调
{
    sendData("D1","D2");
}

void smartHome::on_pushButton_12_clicked()//主卧灯
{
    sendData("D3","D4");
}


void smartHome::on_pushButton_13_clicked()//次卧灯
{
    sendData("E1","E2");
}

void smartHome::on_pushButton_14_clicked()//次卧空调
{
     sendData("E3","E4");
}

void smartHome::on_pushButton_15_clicked()//卫生间空调
{
    sendData("G1","G2");
}

void smartHome::on_toolButton_clicked()
{
    showMinimized();
}


void smartHome::on_toolButton_2_clicked()
{
    TerminalConsole * ter = new TerminalConsole;
    ter->show();
    delete this;
}

void smartHome::on_toolButton_3_clicked()
{
    close();
}

void smartHome::sendData(QString data1,QString data2)
{
    QString dataToSend = data1;
    static int i=0;
    if(i%2==0)
    {

        serialPort->write(dataToSend.toUtf8());
    }

   else if(i%2==1)
    {
         dataToSend = data2;
        serialPort->write(dataToSend.toUtf8());
    }
    i++;
    qDebug()<<dataToSend<<endl;
}

void smartHome::mouseMoveEvent(QMouseEvent *e)
{
    if (e->buttons() & Qt::LeftButton) {
               this->move(this->x() + e->globalX() - p.x(), this->y() + e->globalY() - p.y());
               p = e->globalPos();
           }
}

void smartHome::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
               p = e->globalPos();
    }
}
